package com.loveyukari.utils;

import java.io.IOException;
import java.net.InetAddress;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;

import com.aliyun.mns.model.Message;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.dyvmsapi.model.v20170525.SingleCallByVoiceRequest;
import com.aliyuncs.dyvmsapi.model.v20170525.SingleCallByVoiceResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.loveyukari.support.JsonResult;
import org.springframework.beans.factory.annotation.Value;

/**
*
*yangshaohua
*2016年12月6日下午12:05:59
**/
public class AliYunUtils {

	private static Logger log = LoggerFactory.getLogger(AliYunUtils.class);
	private static String SEND_TALK_NUM = "SMS_83950017";
	private static String SEND_CODE_NUM = "SMS_83430173";
	private static final String accessKeyId = "LTAIFbWmv6wVRvDk";
	private static final String accessKeySecret = "8hkQTME68BDZq9qGEmKIXoug9vnC3o";
    private static String[] CALLED_SHOW_NUM = {"02160555831","057128854831","057128294831","057128834196","057128284831"};



    public static void send(String template, String phone, String param){
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		//初始化ascClient需要的几个参数
		final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
		final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
		//初始化ascClient,暂时不支持多region
		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
					accessKeySecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			IAcsClient acsClient = new DefaultAcsClient(profile);
			SendSmsRequest request = new SendSmsRequest();
			request.setMethod(MethodType.POST);
			request.setPhoneNumbers(phone);
			request.setSignName("小缘");
			request.setTemplateCode(template);
			request.setTemplateParam(param == null ? "{}" : param);
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
			if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
			}
		} catch (Exception e) {
			log.error(phone+":"+e.getMessage(),e);
			e.printStackTrace();
		}
	}


	public static void sendTalk(String phone,String roomId,String text){
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		//初始化ascClient需要的几个参数
		final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
		final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
		//初始化ascClient,暂时不支持多region
		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
			accessKeySecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			IAcsClient acsClient = new DefaultAcsClient(profile);
			 SendSmsRequest request = new SendSmsRequest();
			 request.setMethod(MethodType.POST);
			 request.setPhoneNumbers(phone);
			 request.setSignName("小缘");
			 request.setTemplateCode(SEND_TALK_NUM);
			 request.setTemplateParam("{\"txt\":\""+text+"\", \"room\":\""+roomId+"\"}");
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
			if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
			}
		} catch (Exception e) {
			log.error(phone+":"+e.getMessage(),e);
			e.printStackTrace();
		}
	}
	
	public static JsonResult<String> sendCode(String phone,String code){
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		//初始化ascClient需要的几个参数
		final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
		final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
		//初始化ascClient,暂时不支持多region
		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
			accessKeySecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			IAcsClient acsClient = new DefaultAcsClient(profile);
			 SendSmsRequest request = new SendSmsRequest();
			 request.setMethod(MethodType.POST);
			 request.setPhoneNumbers(phone);
			 request.setSignName("小缘");
			 request.setTemplateCode(SEND_CODE_NUM);
			 request.setTemplateParam("{\"code\":\""+code+"\"}");
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
			if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
				return new JsonResult<String>(0, "发送成功");
			} else {
				log.error(phone+":"+sendSmsResponse.getMessage());
				return new JsonResult<String>(-1, "发送失败",sendSmsResponse.getMessage());
			}
		} catch (Exception e) {
			log.error(phone+":"+e.getMessage(),e);
			return new JsonResult<String>(-1, "发送失败",e.getMessage());
		}
	}
	
	
	
	
	public static boolean callStartLive(String phone,String showNumber){
		final String product = "Dyvmsapi";
       //语音API服务产品域名
        final String domain = "dyvmsapi.aliyuncs.com";
        //需要替换成你的AK信息
        try {
			//初始化acsClient
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			IAcsClient acsClient = new DefaultAcsClient(profile);
			//组装请求对象
			SingleCallByVoiceRequest request = new SingleCallByVoiceRequest();
			//必填-被叫显号,可在语音控制台中找到所购买的显号
			if (StringUtils.isEmpty(showNumber)){
				int index = Math.abs(phone.hashCode()) % CALLED_SHOW_NUM.length;
				showNumber = CALLED_SHOW_NUM[index];
			}
			request.setCalledShowNumber(showNumber);
			//必填-被叫号码
			request.setCalledNumber(phone);
			//必填-语音文件ID
			request.setVoiceCode("7ee39490-3e78-4780-ba69-8530bba99c41.wav");
//        //可选-外部扩展字段
			request.setOutId(phone+","+showNumber);
			//请求失败这里会抛异常
			SingleCallByVoiceResponse singleCallByVoiceResponse = acsClient.getAcsResponse(request);
			if(singleCallByVoiceResponse.getCode()!=null && singleCallByVoiceResponse.getCode().equals("OK")) {
			         //请求成功
				log.info(phone+":"+singleCallByVoiceResponse.getMessage()+",showNumber:"+showNumber);
				return true;
			} else {
				log.error(phone+":"+singleCallByVoiceResponse.getMessage());
				return false;
			}
		} catch (ClientException e) {
			log.error(phone+":"+e.getMessage(),e);
			return false;
		}
	}
	
	public static void callListStartLive(List<String> phones){
		int count = 0;
		HashMap<String, Integer> showNumCountMap = new HashMap<String, Integer>();
		for (String phone : phones) {
			int index = Math.abs(phone.hashCode()) % CALLED_SHOW_NUM.length;
			boolean flag = callStartLive(phone, CALLED_SHOW_NUM[index]);
			if (flag) {
			} else {
				callStartLive(phone, CALLED_SHOW_NUM[index]);
			}
//			Integer numCount = showNumCountMap.get(CALLED_SHOW_NUM[index]);
//			if (numCount == null){
//				numCount = 0;
//			}
//			numCount++;
//			count++;
//			showNumCountMap.put(CALLED_SHOW_NUM[index], numCount);
//			if (numCount >= 30 || count >= 50){
//				try {
//					Thread.sleep(60000);
//					showNumCountMap.clear();
//					count = 0;
//				} catch (Exception e) {
//				}
//			} else {
//				showNumCountMap.put(CALLED_SHOW_NUM[index], numCount);
//			}
		}
	}
	
	
}
